package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.feign.*;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.mapper.AdWmNewsMapper;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.AdWmNewsService;
import com.usian.admin.util.SensitiveWordUtil;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: AdChannelServiceImpl
 * Author:   WGG
 * Date:    2022-11-2022/11/9-16:42
 * Version: 1.0
 * Description:
 */
@Service
@Slf4j
public class AdWmNewsServiceImpl extends ServiceImpl<AdWmNewsMapper, WmNews> implements AdWmNewsService {

    @Autowired
    private WmNewsClient wmNewsClient;

    @Autowired
    private AdArticleClient apArticleClient;

    @Autowired
    private AdArticleConfigClient apArticleConfigClient;

    @Autowired
    private AdArticleContentClient apArticleContentClient;

    @Resource
    private AdChannelMapper adChannelMapper;

    @Autowired
    private ApAuthorClient apAuthorClient;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private GreeTextScan greeTextScan;

    @Autowired
    private FastDFSClient fastDFSClient;

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Autowired
    private AdSensitiveService adSensitiveService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;




    @Override
    public ResponseResult listWmNews(WmNewsDto wmNewsDto) {
        return wmNewsClient.listWmNews(wmNewsDto);
    }

    @Override
    public ResponseResult one(Integer id) {
        //判断参数是否为空
        if (id ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //拿到数据
        ResponseResult one = wmNewsClient.one(id);
        System.out.println(one.getData());
        return one;
    }

    @Override
    public void oneUpdate(Integer id) throws Exception {
        //判断参数是否为空
        System.out.println("-------------public void oneUpdate(Integer id) throws Exception============="+id);
        //拿到数据
        WmNews wmNews  = wmNewsClient.getOneWmNews(id);
        System.out.println("==========================="+wmNews);
        //当状态等于4时，
        if (wmNews.getStatus()==4){
            //添加数据到ap_article ap_article_config ap_article_content
//            saveAll(wmNews);
//            return ;

                //修改文章状态信息
                wmNews.setReason("审核通过，待发布");
                wmNews.setStatus(8);
                wmNewsClient.updateStatusAndReason(wmNews);
                return;

        }
        //当状态等于8时，
        if (wmNews.getStatus()==8&&wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            //添加ap_article
//            saveApArticle(wmNews);
            saveAll(wmNews);
            return ;
        }
        //当状态等于1时
        if (wmNews.getStatus()==1){
            String text = text(wmNews);
            List<String> image = image(wmNews);
            System.out.println("_+_+_++_)+_)+_)+_)_+_"+image);
            System.out.println(wmNews);
            if (!wordScan(wmNews)) return ;
            if (!textScan(text,wmNews)) return ;
            if (!imageScan(image,wmNews)) return ;
            //当前文章的发布时间大于当前
            if (wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                //修改文章状态信息
                wmNews.setReason("审核通过，待发布");
                wmNews.setStatus(8);
                wmNewsClient.updateStatusAndReason(wmNews);
                return;
            }
            //添加数据到ap_article ap_article_config ap_article_content
            saveAll(wmNews);
        }

    }

    //手动审核文本
    public boolean wordScan(WmNews wmNews){
        boolean flag = true;
        List<AdSensitive> all = adSensitiveService.findAll();
        List<String> sensitive = new ArrayList<>();
        for (AdSensitive adSensitive : all) {
            sensitive.add(adSensitive.getSensitives());
        }
        SensitiveWordUtil.initMap(sensitive);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text(wmNews));
        if (map.size()>0){
            flag = false;
            wmNews.setStatus(2);
            wmNews.setReason("文本中有敏感词");
            wmNewsClient.updateStatusAndReason(wmNews);
        }
        return flag;
    }
    //自动审核图片
    public boolean imageScan(List<String> images,WmNews wmNews) throws Exception {
        boolean flag = true;
        Integer status = 0;
        String msg = "";
        //将图片内容转换成byte数组
        ArrayList<byte[]> imageList = new ArrayList<>();
        for (String image : images) {
            String imageName = image.replace(fileServerUrl,"");
            int index = imageName.indexOf("/");
            String groupName = imageName.substring(0,index);
            String imagePath = imageName.substring(index+1);
            byte[] imageByte = fastDFSClient.download(groupName,imagePath);
            imageList.add(imageByte);
        }
        Map map = greenImageScan.imageScan(imageList);
        String result = map.get("suggestion").toString();
        if (result.equals("review")){
            status = 3;
            msg = "内容不确定，需要人工审核";
            flag=false;
        }else if (result.equals("block")){
            status = 2;
            msg = "图片有问题";
            flag=false;
        }
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        if (flag){
            wmNewsClient.updateStatusAndReason(wmNews);
        }
        return flag;
    }
    //自动审核文本
    public boolean textScan(String str,WmNews wmNews) throws Exception {
        boolean flag = true;
        Integer status = 0;
        String msg = "";
        Map map = greeTextScan.greeTextScan(str);
        String result = map.get("suggestion").toString();
        if (result.equals("review")){
            status = 3;
            msg = "内容不确定，需要人工审核";
            flag=false;
        }else if (result.equals("block")){
            status = 2;
            msg = "文字中有敏感词汇";
            flag=false;
        }
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        if (flag){
            wmNewsClient.updateStatusAndReason(wmNews);
        }
        return flag;
    }
    //提取文本
    public String text(WmNews wmNews){
        String str = null;
        List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("text")){
                str+=map.get("value").toString();
            }
        }
        return str;
    }
    //提取图片
    public List<String> image(WmNews wmNews){
        List<String> str = new ArrayList<>();
        List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")){
                str.add(map.get("value").toString());
            }
        }
        return str;
    }
    //添加数据到ap_article ap_article_config ap_article_content
    public void saveAll(WmNews wmNews) throws IOException {
        ApArticle apArticle = saveApArticle(wmNews);
        System.out.println("*****************"+apArticle);
        saveApArticleConfig(wmNews,apArticle);
        saveApArticleContent(wmNews,apArticle);
        wmNews.setReason("审核通过");
        wmNews.setArticleId(apArticle.getId());
        wmNews.setStatus(9);
        wmNewsClient.updateStatusAndReason(wmNews);
        Map map = new HashMap<String,Object>();
        //添加数据成功后保存到es一份
        map.put("id", apArticle.getId());
        map.put("authorId", apArticle.getAuthorId());
        map.put("title", apArticle.getTitle());
        map.put("publishTime", apArticle.getPublishTime());
        map.put("images", apArticle.getImages());
        map.put("layout", apArticle.getLayout());
        ApArticleContent apArticleContent = apArticleContentClient.findById(apArticle.getId());
        if (apArticleContent!=null){
            map.put("content", apArticleContent.getContent());
        }
        IndexRequest request = new IndexRequest("app_info_article").id(apArticle.getId().toString()).source(map);
        restHighLevelClient.index(request, RequestOptions.DEFAULT);
    }
    //添加数据到ap_article_config
    private void saveApArticleConfig(WmNews wmNews, ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(wmNews.getEnable()==1?true:false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigClient.saveArticleConfig(apArticleConfig);
    }
    //添加数据到ap_article_content
    private void saveApArticleContent(WmNews wmNews, ApArticle apArticle)
    {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentClient.saveArticleContent(apArticleContent);
    }

    //添加数据到ap_article
    public ApArticle saveApArticle(WmNews wmNews) throws IOException {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setChannelId(wmNews.getChannelId());
        apArticle.setImages(wmNews.getImages());
        apArticle.setPublishTime(wmNews.getPublishTime());
        apArticle.setCreatedTime(wmNews.getCreatedTime());
        apArticle.setLabels(wmNews.getLabels());
        //查询author_id author_name
        ApAuthor apAuthor = getAuthor(wmNews);
        System.out.println("++++++++++++_+_+_+_"+apAuthor);
        apArticle.setAuthorId(apAuthor.getId());
        apArticle.setAuthorName(apAuthor.getName());
        //查询channel_name
        AdChannel adChannel = getAdChannel(wmNews);
        apArticle.setChannelName(adChannel.getName());
        apArticle = apArticleClient.saveArticle(apArticle);

        return apArticle;
    }
    //查询author_id author_name
    private ApAuthor getAuthor(WmNews wmNews) {
        return apAuthorClient.getByAuthor(wmNews.getUserId());
    }
    //查询channel_name
    private AdChannel getAdChannel(WmNews wmNews) {
        return adChannelMapper.selectById(wmNews.getChannelId());
    }

}
